/*
 * @(#) $Header$
 *
 * Copyright (C) 2011  Daniel Léonard
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

package ca.forklabs.baselib.io;

import java.io.OutputStream;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import ca.forklabs.baselib.util.Algorithm;
import ca.forklabs.baselib.util.Iterators;
import ca.forklabs.baselib.util.UnaryFunction;

import java.io.IOException;

/**
 * Class {@link ForkOutputStream} is an output stream that has multiple sinks.
 * <p>
 * Methods in this class never throw I/O exceptions.  The client may inquire as
 * to whether any errors have occurred by invoking {@link #checkError()}.
 *
 * @author   <a href="mailto:forklabs at gmail.com?subject=ca.forklabs.baselib.io.ForkOutputStream">Daniel Léonard</a>
 * @version $Revision$
 */
public class ForkOutputStream extends AbstractOutputStream {

//---------------------------
// Instance variable
//---------------------------

   /** The sink. */
   private List<OutputStream> sinks = new LinkedList<>();

   /** Tells if an error occurred. */
   private boolean has_error_occured = false;


//---------------------------
// Constructor
//---------------------------

   /**
    * Constructor.
    */
   public ForkOutputStream() {
   // nothing
      }

   /**
    * Constructor.
    * @param   streams   a collection of streams.
    */
   public ForkOutputStream(Iterable<OutputStream> streams) {
      this.addAll(streams);
      }


//---------------------------
// Accessors and mutators
//---------------------------

   /**
    * Gets the list of sinks.
    * @return   the sinks.
    */
   protected List<OutputStream> getSinks() {
      return this.sinks;
      }


//---------------------------
// Instance methods
//---------------------------

   /**
    * Gets an {@link Iterator} on all the sinks.
    * @return   the iterator.
    */
   protected Iterator<OutputStream> getSinkIterator() {
      List<OutputStream> streams = this.getSinks();
      Iterator<OutputStream> iterator = streams.iterator();
      return iterator;
      }

   /**
    * Adds an output stream.
    * @param   stream   the stream.
    */
   public void add(OutputStream stream) {
      List<OutputStream> streams = this.getSinks();
      streams.add(stream);
      }

   /**
    * Adds many output streams.
    * @param   streams   the streams.
    */
   public void addAll(Iterable<OutputStream> streams) {
      Algorithm.copy(streams.iterator(), Iterators.backInserter(this.getSinks()));
      }

   /**
    * Removes the given stream.
    * @param   stream   the stream.
    */
   public void remove(OutputStream stream) {
      List<OutputStream> streams = this.getSinks();
      streams.remove(stream);
      }

   /**
    * Check the error state of this stream. Errors are cumulative; once the
    * stream encounters an error, this routine will return {@code true} on all
    * successive calls.
    * @return    {@code true} if the stream has encountered an error,
    *            {@code false} oterwise.
    */
   public boolean checkError() {
      return this.has_error_occured;
      }

   /**
    * Indicate that an error has occurred.
    */
   protected void setError() {
      this.has_error_occured = true;
      }


//---------------------------
// Overridden methods from java.io.OutputStream
//---------------------------

   /**
    * Writes the given byte into each sink.
    * @param   b   the byte to write.
    */
   @Override
   public void write(int b) {
      byte[] bytes = new byte[] { (byte) b, };
      int off = 0;
      int len = 1;
      this.write(bytes, off, len);
      }

   /**
    * Write the same portion of an array of bytes into each sink.
    * @param   bytes  array of bytes.
    * @param   off   offset from which to start writing characters.
    * @param   len   number of characters to write.
    */
   @Override
   public void write(byte bytes[], int off, int len) {
      Iterator<OutputStream> iter = this.getSinkIterator();

      final byte[] buffer = bytes;
      final int offset = off;
      final int size = len;

      Algorithm.forEach(iter, new UnaryFunction<Void, OutputStream>() {
         @Override
         @SuppressWarnings("resource")
         public Void invoke(OutputStream stream) {
            try {
               stream.write(buffer, offset, size);
               }
            catch (IOException ioe) {
               ForkOutputStream fork_output_stream = ForkOutputStream.this;
               fork_output_stream.setError();
               }
            return null;
            }
         });
      }

   /**
    * Flushes every sink.
    */
   @Override
   public void flush() {
      Iterator<OutputStream> iter = this.getSinkIterator();
      Algorithm.forEach(iter, new UnaryFunction<Void, OutputStream>() {
         @Override
         @SuppressWarnings("resource")
         public Void invoke(OutputStream stream) {
            try {
               stream.flush();
               }
            catch (IOException ioe) {
               ForkOutputStream fork_output_stream = ForkOutputStream.this;
               fork_output_stream.setError();
               }
            return null;
            }
         });
      }


//---------------------------
// Overridden methods from ca.forklabs.baselib.io.AbstractOutputStream
//---------------------------

   /**
    * Closes this stream and every writers.
    */
   @Override
   public void close() {
      Iterator<OutputStream> iter = this.getSinkIterator();
      Algorithm.forEach(iter, new UnaryFunction<Void, OutputStream>() {
         @Override
         @SuppressWarnings("resource")
         public Void invoke(OutputStream stream) {
            try {
               stream.close();
               }
            catch (IOException ioe) {
               ForkOutputStream fork_output_stream = ForkOutputStream.this;
               fork_output_stream.setError();
               }
            return null;
            }
         });

      super.close();
      }

   }
